package cn.elricyu.kf.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;

import cn.elricyu.kf.bean.User;
import cn.elricyu.kf.exception.DaoException;

public class UserDAO extends JpaDaoSupport {

	public User SaveUser(User user) throws DaoException {
		try {
			getJpaTemplate().persist(user);
		} catch (Exception e) {
			throw new DaoException("UserDAO.SaveUser", e);
		}
		return user;
	}

	public User UpdateUser(User user) throws DaoException {
		try {
			getJpaTemplate().merge(user);
		} catch (Exception e) {
			throw new DaoException("UserDAO.UpdateUser", e);
		}
		return user;
	}

	public void deleteUser(Long id) throws DaoException {
		try {
			getJpaTemplate().remove(getUser(id));
		} catch (Exception e) {
			throw new DaoException("UserDAO.deleteUser", e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() throws DaoException {
		try {
			return (List<User>) getJpaTemplate().execute(new JpaCallback() {
				public Object doInJpa(EntityManager em)
						throws PersistenceException {
					return em.createNamedQuery("FarmUser.getAllUser")
							.getResultList();
				}
			});
		} catch (Exception e) {
			throw new DaoException("UserDAO.getAllUsers", e);
		}

	}

	public User getUser(final Long id) throws DaoException {
		try {
			return (User) getJpaTemplate().execute(new JpaCallback() {
				public Object doInJpa(EntityManager em)
						throws PersistenceException {
					return em.find(User.class, id);
				}
			});
		} catch (Exception e) {
			throw new DaoException("UserDAO.getUser", e);
		}
	}

	public User getUserByUserId(final String userId) throws DaoException {
		try {
			List<User> userList = (List<User>) getJpaTemplate().execute(
					new JpaCallback() {
						public Object doInJpa(EntityManager em)
								throws PersistenceException {
							return em.createNamedQuery(
									"FarmUser.findUserByUserId").setParameter(
									"userId", userId).getResultList();
						}
					});

			if (userList != null && userList.size() > 0) {
				return userList.get(0);
			}
			return null;
		} catch (Exception e) {
			throw new DaoException("UserDAO.getUserByUserId", e);
		}
	}

}
